package cn.italkcloud.cph.controller;

import cn.italkcloud.cph.config.sys.Response;
import cn.italkcloud.cph.config.sys.ResponseCode;
import cn.italkcloud.cph.constants.enums.PermViewEnum;
import cn.italkcloud.cph.entity.dto.UserAuthDTO;
import cn.italkcloud.cph.entity.dto.UserDTO;
import cn.italkcloud.cph.entity.req.LoginReq;
import cn.italkcloud.cph.entity.req.SearchReq;
import cn.italkcloud.cph.helper.AuthHelper;
import cn.italkcloud.cph.helper.UserHelper;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author dominate
 * @since 2025/3/19
 **/
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {

    /**
     * 登录
     * 1.查询用户
     * 2.验证用户
     * 3.设置登录
     * 4.返回JwtToken
     *
     * @return JwtToken
     */
    @PostMapping("/login")
    @ResponseBody
    public Response<String> login(
            @RequestBody LoginReq req
    ) {
        int accountId = UserHelper.findAccount(req.getAccount());
        // 无效用户直接返回
        if (0 == accountId) {
            return Response.code(ResponseCode.LOGIN_SIGN_REFUSED);
        }
        if (!UserHelper.checkPassword(accountId, req.getPassword())) {
            return Response.code(ResponseCode.LOGIN_SIGN_REFUSED);
        }
        UserAuthDTO user = UserHelper.prepareUser(accountId);
        return Response.data(AuthHelper.grantAuth(user));
    }

    /**
     * 登出
     * 使 JwtToken 失效
     *
     * @return 固定返回成功
     */
    @PostMapping("/logout")
    @ResponseBody
    public Response<String> logout(
    ) {
        try {
            AuthHelper.setInvalid(getToken());
        } catch (Exception e) {
            // 退出登陆，忽略失败
        }
        return Response.success();
    }

    /**
     * 解析Token菜单路径
     *
     * @return 菜单路径列表
     */
    @PostMapping("/menu")
    @ResponseBody
    public Response<List<String>> parseMenu() {
        UserAuthDTO userAuth = getUser();
        // 仅解析当前 JwtToken 里的菜单权限
        return Response.data(PermViewEnum.getPathList(userAuth.getViewPermIds()));
    }

    /**
     * 解析Token菜单路径
     *
     * @return 菜单路径列表
     */
    @PostMapping("/user")
    @ResponseBody
    public Response<UserAuthDTO> parseUser() {
        UserAuthDTO userAuth = getUser();
        if (null == userAuth) {
            return Response.code(ResponseCode.IDENTITY_STATE_WRONG);
        }
        return Response.data(userAuth);
    }

    /**
     * 解析Token菜单路径
     *
     * @return 菜单路径列表
     */
    @PostMapping("/search")
    @ResponseBody
    public Response<List<UserDTO>> search(@RequestBody SearchReq req) {
        return Response.data(UserHelper.search(req.getKeyword()));
    }
}
